/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jjsoft.celularessuc.gco.ui;

import com.jjsoft.celularessuc.gco.mdl.Detallefactura;
import com.jjsoft.celularessuc.gco.mdl.Serie;
import com.jjsoft.celularessuc.gco.mdl.Sucursal;
import com.jjsoft.celularessuc.gco.neg.ArticuloManager;
import com.jjsoft.celularessuc.gco.neg.ArticuloSucursalManager;
import com.jjsoft.celularessuc.gco.neg.SerieManager;
import com.jjsoft.celularessuc.gco.util.CNumeros;
import com.jjsoft.celularessuc.gco.util.CSelecciones;
import com.jjsoft.celularessuc.gco.util.MiModelo;
import com.jjsoft.celularessuc.gco.util.configuraciones;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

/**
 *
 * @author Johnny
 */
public class VTransferenciaDeArticulos extends javax.swing.JFrame {

    /**
     * Creates new form VTransferenciaDeArchivoos
     */
    ArticuloManager am = new ArticuloManager();
    Sucursal origen;
    Sucursal destino;
    List<Detallefactura> listaDetalle;
    MiModelo modelo = new MiModelo();
    SerieManager sm = new SerieManager();

    public VTransferenciaDeArticulos(Sucursal origen, Sucursal destino) {
        initComponents();
        this.origen = origen;
        this.destino = destino;
        txtDe.setText(origen.getNombre());
        txtA.setText(destino.getNombre());
        listaDetalle = new ArrayList();
        String[] identificadores = {"CANT", "DESCRIPCION", "P. UNIT", "V. VENTA"};
        this.modelo.setColumnIdentifiers(identificadores);
        this.dtgFactura.setModel(this.modelo);
        this.dtgFactura.getColumn("CANT").setPreferredWidth(30);
        this.dtgFactura.getColumn("DESCRIPCION").setPreferredWidth(330);
        this.dtgFactura.getColumn("P. UNIT").setPreferredWidth(50);
        this.dtgFactura.getColumn("V. VENTA").setPreferredWidth(50);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mnuTransferencia = new javax.swing.JPopupMenu();
        mnuVerSeries = new javax.swing.JMenuItem();
        jLabel9 = new javax.swing.JLabel();
        txtCodigo = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        txtCantidad = new javax.swing.JSpinner();
        cmdAgregar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        dtgFactura = new javax.swing.JTable();
        cmdQuitar = new javax.swing.JButton();
        cmdGuardar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtDe = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtA = new javax.swing.JTextField();

        mnuVerSeries.setLabel("Ver series disponibles");
        mnuTransferencia.add(mnuVerSeries);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel9.setText("Codigo:");

        txtCodigo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCodigoActionPerformed(evt);
            }
        });
        txtCodigo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtCodigoKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtCodigoKeyReleased(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/search-database.png"))); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        txtCantidad.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1)));

        cmdAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/add.png"))); // NOI18N
        cmdAgregar.setText("Agregar");
        cmdAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdAgregarActionPerformed(evt);
            }
        });

        dtgFactura.setComponentPopupMenu(mnuTransferencia);
        dtgFactura.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jScrollPane1.setViewportView(dtgFactura);

        cmdQuitar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/delete.png"))); // NOI18N
        cmdQuitar.setText("    Quitar");
        cmdQuitar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdQuitarActionPerformed(evt);
            }
        });

        cmdGuardar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        cmdGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/save.png"))); // NOI18N
        cmdGuardar.setText("     GUARDAR");
        cmdGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdGuardarActionPerformed(evt);
            }
        });

        jLabel1.setText("Cantidad:");

        jLabel2.setFont(new java.awt.Font("Ubuntu", 1, 18)); // NOI18N
        jLabel2.setText("Transferencia de Articulos");

        jLabel3.setText("De:");

        txtDe.setEditable(false);

        jLabel4.setText("A:");

        txtA.setEditable(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jLabel2)
                .addGap(178, 178, 178))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(cmdGuardar))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(cmdQuitar))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(25, 25, 25)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel9)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(txtDe))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(cmdAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(38, 38, 38)
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtA, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap(163, Short.MAX_VALUE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 572, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap()))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(jLabel2)
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtDe, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(txtA, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel9)
                        .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jButton1)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1))
                    .addComponent(cmdAgregar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 231, Short.MAX_VALUE)
                .addComponent(cmdQuitar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cmdGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(138, 138, 138)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(95, Short.MAX_VALUE)))
        );

        setSize(new java.awt.Dimension(608, 483));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void txtCodigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCodigoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCodigoActionPerformed

    private void txtCodigoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodigoKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == 10) {

            CSelecciones.articulo = am.buscarPorCodigo(txtCodigo.getText(), origen);

            if (CSelecciones.articulo == null) {
                JOptionPane.showMessageDialog(rootPane, "No se encontro el artículo", "Error", JOptionPane.ERROR_MESSAGE);
            } else {
            }
        }
    }//GEN-LAST:event_txtCodigoKeyPressed

    private void txtCodigoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodigoKeyReleased
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCodigoKeyReleased

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        CSelecciones.texto1 = txtCodigo;
        CSelecciones.texto2 = new JTextField();
        new VSeleccionArticulo(origen).setVisible(true);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void cmdAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdAgregarActionPerformed
        // TODO add your handling code here:
        if (CSelecciones.articulo != null) {
            double precio = 0;
            precio = CSelecciones.articulo.getPventa();
            if (CSelecciones.articulo.getStock() < Integer.parseInt(String.valueOf(txtCantidad.getValue()))) {
                JOptionPane.showMessageDialog(rootPane, "No existen sufucientes artículos en stock");
                return;
            }
            String serie = buscarSerie();
            if (serie == null) {
                limpiaTodo();
                return;
            }
            if (serie.equals("")) {
                agregarArticulo(precio, serie, Integer.parseInt(String.valueOf(txtCantidad.getValue())));
            } else {
                int cantidadAgregar = Integer.parseInt(String.valueOf(txtCantidad.getValue()));
                txtCantidad.setValue(1);
                for (int i = 0; i < cantidadAgregar - 1; i++) {
                    if (serie != null) {
                        agregarArticulo(precio, serie, 1);
                    }

                    serie = buscarSerie();
                }
                if (serie != null) {
                    agregarArticulo(precio, serie, 1);
                }
            }
            limpiaTodo();
        } else {
            JOptionPane.showMessageDialog(rootPane, "Primero Seleccione un artículo", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
    }//GEN-LAST:event_cmdAgregarActionPerformed

    private void cmdQuitarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdQuitarActionPerformed
        // TODO add your handling code here:

        if (dtgFactura.getSelectedRow() != -1) {
            if (JOptionPane.showConfirmDialog(rootPane, "Esta seguro", "Quitar Articulo", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                int i = dtgFactura.getSelectedRow();
                modelo.removeRow(i);
                listaDetalle.remove(i);
            }

        } else {
            JOptionPane.showMessageDialog(rootPane, "Primero Seleccione un articulo", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_cmdQuitarActionPerformed

    private void cmdGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdGuardarActionPerformed
        // TODO add your handling code here
        if (listaDetalle.size() > 0) {
            if (JOptionPane.showConfirmDialog(rootPane, "Esta seguro", "Guardar Transferencia", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
                ArticuloSucursalManager asm = new ArticuloSucursalManager();
                asm.transferirArticulos(origen, destino, listaDetalle);
                JOptionPane.showMessageDialog(rootPane, "Operación realizada correctamente","transerir artículos",JOptionPane.INFORMATION_MESSAGE);
                this.dispose();
            }
        } else {
            JOptionPane.showMessageDialog(rootPane, "No ha agregado artículos a transferir");
        }
        
    }//GEN-LAST:event_cmdGuardarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VTransferenciaDeArticulos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VTransferenciaDeArticulos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VTransferenciaDeArticulos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VTransferenciaDeArticulos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VTransferenciaDeArticulos(null, null).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cmdAgregar;
    private javax.swing.JButton cmdGuardar;
    private javax.swing.JButton cmdQuitar;
    private javax.swing.JTable dtgFactura;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPopupMenu mnuTransferencia;
    private javax.swing.JMenuItem mnuVerSeries;
    private javax.swing.JTextField txtA;
    private javax.swing.JSpinner txtCantidad;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JTextField txtDe;
    // End of variables declaration//GEN-END:variables
    private void agregarArticulo(double precio, String serie, int cantidad) {
        boolean existe = false;
        if (serie.equals("")) {
            for (int i = 0; i < listaDetalle.size(); i++) {

                if (listaDetalle.get(i).getIdArticulo().equals(CSelecciones.articulo) && listaDetalle.get(i).getPrecioVenta() == precio) {
                    existe = true;
                    int nuevaCant = listaDetalle.get(i).getCantidad() + cantidad;
                    if (nuevaCant > CSelecciones.articulo.getStock()) {

                        JOptionPane.showMessageDialog(rootPane, "No existen suficientes artículos en Stock", "Error", JOptionPane.ERROR_MESSAGE);
                        limpiaTodo();
                        return;
                    }
                    listaDetalle.get(i).setCantidad(nuevaCant);
                    dtgFactura.setValueAt(nuevaCant, i, 0);
                    dtgFactura.setValueAt(CNumeros.redondear(precio * nuevaCant), i, 3);


                    break;
                }
            }
        }
        if (!existe) {
            Detallefactura detallefactura = new Detallefactura();
            detallefactura.setCantidad(cantidad);
            detallefactura.setIdArticulo(CSelecciones.articulo);
            detallefactura.setIva(0);
            detallefactura.setSerie(serie);
            detallefactura.setPrecioVenta(precio);
            listaDetalle.add(detallefactura);
            String desc = detallefactura.getIdArticulo().getDescripcion() + " " + detallefactura.getIdArticulo().getMarca() + " " + detallefactura.getIdArticulo().getModelo();
            if (!serie.equals("")) {
                desc = desc + "SN: " + serie;
            }
            String[] producto = {detallefactura.getCantidad().toString(), desc, String.valueOf(CNumeros.redondear(precio)), String.valueOf(CNumeros.redondear(precio * cantidad))};
            modelo.addRow(producto);

        }
    }

    private void limpiaTodo() {
        CSelecciones.articulo = null;
        txtCodigo.setText("");
        txtCantidad.setValue(1);
    }

    private String buscarSerie() {
        String serie = "";
        List<Serie> listaSeries = sm.buscarSeries(CSelecciones.articulo, origen);

        if (listaSeries != null && !listaSeries.isEmpty()) {
            serie = JOptionPane.showInputDialog("Ingrese un numero de serie");
            if (serie == null) {
                limpiaTodo();
                return null;
            } else {
                if (!sm.buscaSerie(CSelecciones.articulo, origen, serie)) {
                    JOptionPane.showMessageDialog(rootPane, "No existe ese número de serie");
                    limpiaTodo();
                    return null;
                } else {
                    for (int i = 0; i < listaDetalle.size(); i++) {
                        if (listaDetalle.get(i).getSerie().equals(serie)) {
                            JOptionPane.showMessageDialog(rootPane, "Ya ha ingresado ese número de serie");
                            limpiaTodo();
                            return null;
                        }
                    }
                }


            }
            return serie;
        }
        return serie;
    }
}
